package com.commerce.common.exception;

import com.commerce.common.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.reactive.config.WebFluxConfigurer;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * WebFlux环境下的全局异常处理器
 * 仅在WebFlux环境下生效
 */
@Slf4j
@RestControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.REACTIVE)
@ConditionalOnClass(WebFluxConfigurer.class)
@Order(-2)
public class WebFluxGlobalExceptionHandler {

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public Mono<ResponseEntity<Result<String>>> handleException(Exception e, ServerWebExchange exchange) {
        log.error("请求URL: {}, 发生异常: ", exchange.getRequest().getURI(), e);
        Result<String> result = Result.error("系统异常，请稍后重试");
        return Mono.just(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .contentType(MediaType.APPLICATION_JSON)
                .body(result));
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Mono<ResponseEntity<Result<String>>> handleBusinessException(BusinessException e, ServerWebExchange exchange) {
        log.error("请求URL: {}, 业务异常: {}", exchange.getRequest().getURI(), e.getMessage());
        Result<String> result = Result.error(e.getCode(), e.getMessage());
        return Mono.just(ResponseEntity.status(HttpStatus.BAD_REQUEST)
                .contentType(MediaType.APPLICATION_JSON)
                .body(result));
    }
} 